package com.xxx.delayjob.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * rocketmq延时消息
 * https://mp.weixin.qq.com/s/TI6ba39T6gtn5l87Gx55sg
 */
@RestController
@Slf4j
public class RocketMQDelayTaskController {

    @Resource
    private DefaultMQProducer producer;

    /**
     * http://localhost:8080/rocketmq/add?task=sanyou
     */
    @GetMapping("/rocketmq/add")
    public void addTask(@RequestParam("task") String task) throws Exception {
        // 封装Message对象：指定topic、tags、消息体二进制信息
        Message msg = new Message("sanyouDelayTaskTopic", "TagA", task.getBytes(RemotingHelper.DEFAULT_CHARSET));
        // 设置延时等级，总共有18个等级，等级2代表延时5s
        msg.setDelayTimeLevel(2);
        // 发送消息并得到消息的发送结果
        log.info("提交延迟任务");
        producer.send(msg);
    }

}
